package com.atguigu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.atguigu.dto.system.AssginRoleDto;
import com.atguigu.dto.system.SysUserDto;
import com.atguigu.exception.ResultException;
import com.atguigu.mapper.SysUserMapper;
import com.atguigu.mapper.SysUserRoleMapper;
import com.atguigu.service.SysUserService;
import com.atguigu.dto.system.LoginDto;
import com.atguigu.entity.system.SysUser;
import com.atguigu.vo.common.ResultCodeEnum;
import com.atguigu.vo.system.LoginVo;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SysUserServiceImpl implements SysUserService {
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public LoginVo login(LoginDto loginDto) {
        // 验证码验证
//        String captcha = loginDto.getCaptcha();
//        String codeKey = loginDto.getCodeKey();
//        String redisCode = redisTemplate.opsForValue().get("redis:code" + codeKey);
//        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(captcha, redisCode)){
//            throw new ResultException(ResultCodeEnum.VALIDATECODE_ERROR);
//        }
//        redisTemplate.delete("redis:code" + codeKey);

        // 用户名、密码验证
        String userName = loginDto.getUserName();
        SysUser sysUser = sysUserMapper.selectUserInfoByUserName(userName);

        if (sysUser == null) {
            // throw new RuntimeException("用户名不存在");
            throw new ResultException(ResultCodeEnum.LOGIN_ERROR);
        }
        String password = sysUser.getPassword();
        String fontPassword = DigestUtils.md5DigestAsHex(loginDto.getPassword().getBytes());

        if (!fontPassword.equals(password)) {
            // throw new RuntimeException("密码不正确");
            throw new ResultException(ResultCodeEnum.LOGIN_ERROR);
        }
        String token = UUID.randomUUID().toString().replace("-", "");

        redisTemplate.opsForValue().set(token, JSON.toJSONString(sysUser), 7, TimeUnit.DAYS);
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
        String userInfoString = redisTemplate.opsForValue().get(token);
        SysUser sysUser = JSON.parseObject(userInfoString, SysUser.class);
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete(token);
    }

    @Override
    public PageInfo<SysUser> page(Integer current, Integer limit, SysUserDto sysUserDto) {
        PageHelper.startPage(current, limit);
        List<SysUser> userList = sysUserMapper.page(sysUserDto);
        PageInfo<SysUser> sysUserPageInfo = new PageInfo<>(userList);
        return sysUserPageInfo;
    }

    @Override
    public void submit(SysUser sysUser) {
        SysUser dbUserName = sysUserMapper.selectUserInfoByUserName(sysUser.getUserName());
        if (dbUserName != null) {
            throw new ResultException(ResultCodeEnum.USER_NAME_IS_EXISTS);
        }

        String newPassword = DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes());
        sysUser.setPassword(newPassword);

        sysUserMapper.submit(sysUser);
    }

    @Override
    public void remove(long userId) {
        sysUserMapper.remove(userId);

    }

    @Override
    public void update(SysUser sysUser) {
        sysUserMapper.update(sysUser);
    }

    @Override
    public void doAssign(AssginRoleDto assginRoleDto) {
        Long userId = assginRoleDto.getUserId();
        sysUserRoleMapper.removerRoleByUserId(userId);
        List<Long> roleIdList = assginRoleDto.getRoleIdList();
        for (Long roleId:roleIdList) {
            sysUserRoleMapper.add(roleId,userId);
        }
    }
}
